#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include "list.h" /* A modified Linux kernal linked list */

FILE *files[255];
size_t file_num = 0;

struct list_node
{
  char c;
  struct list_head head;
};

struct tuple
{
  int num;
  char c;
};

void unzip(struct list_head *head)
{
  for (size_t i = 0; i < file_num; ++i)
  {
    int read_number = 0;
    struct tuple tmp;
    while ((read_number = fread(&tmp, 5, 1, files[i])) == 1)
    {
      for (size_t i = 0; i < tmp.num; ++i)
      {
        struct list_node *node = malloc(sizeof(struct list_node));
        node->c = tmp.c;
        list_add_tail(&(node->head), head);
      }
    }
  }
}

int main(int argc, char *const argv[])
{
  if (argc <= 1)
  {
    fprintf(stdout, "seuunzip: file1 [file2 ...]\n");
    exit(EXIT_FAILURE);
  }

  for (size_t i = 1; i < argc; ++i)
  {
    files[i - 1] = fopen(argv[i], "r");
    file_num++;
    if (files[i - 1] == NULL)
    {
      fprintf(stderr, "Can not read file %s\n", argv[i]);
      exit(EXIT_FAILURE);
    }
  }

  LIST_HEAD(head);
  unzip(&head);

  struct list_head *iter;
  struct list_node *node;
  struct list_head *tmp;
  for (iter = head.next; iter != &head; iter = tmp)
  {
    tmp = iter->next;
    node = list_entry(iter, struct list_node, head);
    fwrite(node, sizeof(char), 1, stdout);
    free(node);
  }
}